<template>
  <div class="product-management">
    <div class="page-header">
      <h2>商品管理</h2>
      <div>
        <button class="btn btn-primary" @click="showCreateModal">➕ 新增商品</button>
        <button class="btn btn-default" @click="loadProducts">🔄 刷新</button>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="card">
      <div v-if="loading" class="loading">加载中...</div>
      
      <div v-else-if="products.length === 0" class="empty">
        暂无商品数据
      </div>

      <div v-else>
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>商品图片</th>
              <th>商品名称</th>
              <th>价格</th>
              <th>分类</th>
              <th>库存</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="product in products" :key="product.id">
              <td>{{ product.id }}</td>
              <td>
                <div v-if="product.image && product.image.length > 0" class="product-images-list">
                  <img 
                    v-for="(img, idx) in (Array.isArray(product.image) ? product.image : [product.image])" 
                    :key="idx"
                    :src="img" 
                    :alt="product.name"
                    class="product-thumb"
                    v-if="idx < 3"
                  />
                  <span v-if="product.image.length > 3" class="more-images">+{{ product.image.length - 3 }}</span>
                </div>
                <span v-else class="no-image">-</span>
              </td>
              <td>{{ product.name }}</td>
              <td>¥{{ product.price }}</td>
              <td>{{ product.category_name || '-' }}</td>
              <td>{{ product.stock === -1 ? '不限' : product.stock }}</td>
              <td>
                <span :class="['status-tag', product.status === 1 ? 'status-paid' : 'status-cancelled']">
                  {{ product.status === 1 ? '上架中' : '已下架' }}
                </span>
              </td>
              <td>{{ formatDate(product.created_at) }}</td>
              <td>
                <div class="actions">
                  <button class="btn btn-default btn-sm" @click="editProduct(product)">
                    编辑
                  </button>
                  <button class="btn btn-primary btn-sm" @click="manageSpecs(product)">
                    规格
                  </button>
                  <button class="btn btn-danger btn-sm" @click="deleteProduct(product)">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 创建/编辑弹窗 -->
    <div v-if="showModal" class="modal" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ editingProduct ? '编辑商品' : '新增商品' }}</h3>
          <button class="close-btn" @click="closeModal">✕</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>商品名称 *</label>
            <input v-model="formData.name" type="text" placeholder="请输入商品名称" />
          </div>
          <div class="form-group">
            <label>商品描述</label>
            <textarea v-model="formData.description" placeholder="请输入商品描述"></textarea>
          </div>
          <div class="form-group">
            <label>商品详情</label>
            <textarea v-model="formData.detail" placeholder="请输入商品详情" rows="4"></textarea>
          </div>
          <div class="form-group">
            <label>价格 *</label>
            <input v-model.number="formData.price" type="number" step="0.01" placeholder="请输入价格" />
          </div>
          <div class="form-group">
            <label>分类 *</label>
            <select v-model.number="formData.category_id">
              <option value="">请选择分类</option>
              <option v-for="cat in categories" :key="cat.id" :value="cat.id">
                {{ cat.name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>商品图片/视频（可多个）</label>
            <div class="upload-section">
              <!-- 媒体文件列表预览 -->
              <div v-if="formData.images && formData.images.length > 0" class="media-list">
                <div 
                  v-for="(media, index) in formData.images" 
                  :key="index"
                  class="media-item"
                >
                  <img v-if="isImageUrl(media)" :src="media" alt="预览" />
                  <video v-else-if="isVideoUrl(media)" :src="media" controls></video>
                  <button 
                    type="button" 
                    class="remove-media-btn" 
                    @click="removeMedia(index)"
                    title="删除"
                  >
                    ✕
                  </button>
                  <button 
                    type="button" 
                    class="move-media-btn move-up" 
                    @click="moveMedia(index, -1)"
                    :disabled="index === 0"
                    title="上移"
                  >
                    ↑
                  </button>
                  <button 
                    type="button" 
                    class="move-media-btn move-down" 
                    @click="moveMedia(index, 1)"
                    :disabled="index === formData.images.length - 1"
                    title="下移"
                  >
                    ↓
                  </button>
                </div>
              </div>
              
              <div class="upload-controls">
                <input 
                  ref="fileInput" 
                  type="file" 
                  accept="image/*,video/*" 
                  multiple
                  style="display: none"
                  @change="handleFileSelect"
                />
                <button 
                  type="button" 
                  class="btn btn-default" 
                  @click="$refs.fileInput.click()"
                  :disabled="uploading"
                >
                  {{ uploading ? '上传中...' : '📷 选择图片/视频（可多选）' }}
                </button>
                <span v-if="uploadError" class="upload-error">{{ uploadError }}</span>
              </div>
              <div class="upload-tip">
                <small>支持多个图片/视频，可以混合上传。最多10个文件，单个文件最大50MB</small>
              </div>
            </div>
          </div>
          <div class="form-group">
            <label>库存（-1表示不限）</label>
            <input v-model.number="formData.stock" type="number" placeholder="库存数量" />
          </div>
          <div class="form-group">
            <label>是否虚拟商品</label>
            <select v-model.number="formData.is_virtual">
              <option :value="1">是</option>
              <option :value="0">否</option>
            </select>
          </div>
          <div class="form-group">
            <label>网盘地址（虚拟商品）</label>
            <input v-model="formData.download_url" type="text" placeholder="请输入网盘下载地址" />
          </div>
          <div class="form-group">
            <label>状态</label>
            <select v-model.number="formData.status">
              <option :value="1">上架</option>
              <option :value="0">下架</option>
            </select>
          </div>
          <div class="form-actions">
            <button class="btn btn-default" @click="closeModal">取消</button>
            <button class="btn btn-primary" @click="submitForm">确定</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 规格管理弹窗 -->
    <div v-if="showSpecModal" class="modal" @click="closeSpecModal">
      <div class="modal-content modal-large" @click.stop>
        <div class="modal-header">
          <h3>规格管理 - {{ currentProduct?.name }}</h3>
          <button class="close-btn" @click="closeSpecModal">✕</button>
        </div>
        <div class="modal-body">
          <!-- 规格列表 -->
          <div class="spec-list">
            <div class="spec-list-header">
              <h4>已有规格</h4>
              <button class="btn btn-primary btn-sm" @click="showAddSpec">➕ 添加规格</button>
            </div>
            
            <div v-if="specs.length === 0" class="empty">
              暂无规格配置
            </div>
            
            <table v-else>
              <thead>
                <tr>
                  <th>规格名称</th>
                  <th>规格值</th>
                  <th>价格</th>
                  <th>库存</th>
                  <th>排序</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="spec in specs" :key="spec.id">
                  <td>{{ spec.spec_name }}</td>
                  <td>{{ spec.spec_value }}</td>
                  <td>{{ spec.price ? '¥' + spec.price : '使用商品价格' }}</td>
                  <td>{{ spec.stock === -1 ? '不限' : spec.stock }}</td>
                  <td>{{ spec.sort_order }}</td>
                  <td>
                    <span :class="['status-tag', spec.status === 1 ? 'status-paid' : 'status-cancelled']">
                      {{ spec.status === 1 ? '启用' : '禁用' }}
                    </span>
                  </td>
                  <td>
                    <div class="actions">
                      <button class="btn btn-default btn-sm" @click="editSpec(spec)">编辑</button>
                      <button class="btn btn-danger btn-sm" @click="deleteSpec(spec)">删除</button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 添加/编辑规格表单 -->
          <div v-if="showSpecForm" class="spec-form">
            <h4>{{ editingSpec ? '编辑规格' : '添加规格' }}</h4>
            <div class="form-group">
              <label>规格名称 *</label>
              <input v-model="specFormData.spec_name" type="text" placeholder="如：颜色、尺寸、套餐版本" />
            </div>
            <div class="form-group">
              <label>规格值 *</label>
              <input v-model="specFormData.spec_value" type="text" placeholder="如：红色、L码、标准版" />
            </div>
            <div class="form-group">
              <label>价格（留空使用商品原价）</label>
              <input v-model.number="specFormData.price" type="number" step="0.01" placeholder="该规格的价格" />
            </div>
            <div class="form-group">
              <label>库存（-1表示不限）</label>
              <input v-model.number="specFormData.stock" type="number" placeholder="该规格的库存" />
            </div>
            <div class="form-group">
              <label>排序权重</label>
              <input v-model.number="specFormData.sort_order" type="number" placeholder="数字越大越靠前" />
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model.number="specFormData.status">
                <option :value="1">启用</option>
                <option :value="0">禁用</option>
              </select>
            </div>
            <div class="form-actions">
              <button class="btn btn-default" @click="cancelSpecForm">取消</button>
              <button class="btn btn-primary" @click="submitSpecForm">保存</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getProductsAdmin, createProduct, updateProduct, deleteProduct as deleteProductApi, uploadProductImage, uploadProductImages } from '../api/productAdmin';
import { getCategories } from '../api/category';
import { getSpecs, createSpec as createSpecApi, updateSpec as updateSpecApi, deleteSpec as deleteSpecApi } from '../api/spec';

const products = ref([]);
const categories = ref([]);
const loading = ref(false);
const showModal = ref(false);
const editingProduct = ref(null);
const fileInput = ref(null);
const uploading = ref(false);
const uploadError = ref('');
const formData = ref({
  name: '',
  description: '',
  detail: '',
  price: 0,
  category_id: '',
  images: [], // 改为数组，支持多个图片/视频
  stock: -1,
  is_virtual: 1,
  download_url: '',
  status: 1
});

// 规格管理相关状态
const showSpecModal = ref(false);
const currentProduct = ref(null);
const specs = ref([]);
const showSpecForm = ref(false);
const editingSpec = ref(null);
const specFormData = ref({
  spec_name: '',
  spec_value: '',
  price: null,
  stock: -1,
  sort_order: 0,
  status: 1
});

const loadProducts = async () => {
  loading.value = true;
  try {
    const res = await getProductsAdmin();
    if (res.success) {
      products.value = res.data.list || res.data || [];
    } else {
      alert(res.message || '加载失败');
    }
  } catch (error) {
    console.error('加载商品失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

const loadCategories = async () => {
  try {
    const res = await getCategories();
    if (res.success) {
      categories.value = res.data.list || res.data || [];
    }
  } catch (error) {
    console.error('加载分类失败:', error);
  }
};

const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  return dateStr.replace('T', ' ').substring(0, 19);
};

const showCreateModal = () => {
  editingProduct.value = null;
  formData.value = {
    name: '',
    description: '',
    detail: '',
    price: 0,
    category_id: '',
    images: [],
    stock: -1,
    is_virtual: 1,
    download_url: '',
    status: 1
  };
  showModal.value = true;
};

const editProduct = (product) => {
  editingProduct.value = product;
  
  // 处理图片字段：支持单个URL或JSON数组
  let images = [];
  if (product.image) {
    try {
      const parsed = JSON.parse(product.image);
      images = Array.isArray(parsed) ? parsed : [parsed];
    } catch {
      images = [product.image];
    }
  }
  
  formData.value = {
    name: product.name || '',
    description: product.description || '',
    detail: product.detail || '',
    price: product.price || 0,
    category_id: product.category_id || '',
    images: images,
    stock: product.stock !== undefined ? product.stock : -1,
    is_virtual: product.is_virtual !== undefined ? product.is_virtual : 1,
    download_url: product.download_url || '',
    status: product.status !== undefined ? product.status : 1
  };
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
  editingProduct.value = null;
};

const submitForm = async () => {
  if (!formData.value.name || !formData.value.price || !formData.value.category_id) {
    alert('请填写商品名称、价格和分类');
    return;
  }

  try {
    // 准备提交数据
    const submitData = {
      ...formData.value,
      images: formData.value.images.length > 0 ? formData.value.images : null
    };
    
    let res;
    if (editingProduct.value) {
      res = await updateProduct(editingProduct.value.id, submitData);
    } else {
      res = await createProduct(submitData);
    }

    if (res.success) {
      alert('操作成功');
      closeModal();
      loadProducts();
    } else {
      alert(res.message || '操作失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

const deleteProduct = async (product) => {
  if (!confirm(`确定要删除商品"${product.name}"吗？`)) return;

  try {
    const res = await deleteProductApi(product.id);
    if (res.success) {
      alert('删除成功');
      loadProducts();
    } else {
      alert(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

// 判断是否为图片URL
const isImageUrl = (url) => {
  if (!url) return false;
  return /\.(jpg|jpeg|png|gif|webp|bmp|svg)(\?.*)?$/i.test(url) || url.startsWith('data:image/');
};

// 判断是否为视频URL
const isVideoUrl = (url) => {
  if (!url) return false;
  return /\.(mp4|webm|ogg|mov|avi)(\?.*)?$/i.test(url) || url.startsWith('data:video/');
};

// 处理文件选择（支持多文件）
const handleFileSelect = async (event) => {
  const files = event.target.files;
  if (!files || files.length === 0) return;

  // 验证文件数量和大小
  const maxFiles = 10;
  const maxSize = 50 * 1024 * 1024; // 50MB
  const fileArray = Array.from(files);

  if (fileArray.length > maxFiles) {
    alert(`最多只能选择${maxFiles}个文件`);
    return;
  }

  // 验证每个文件
  for (const file of fileArray) {
    const fileType = file.type;
    const isImage = fileType.startsWith('image/');
    const isVideo = fileType.startsWith('video/');
    
    if (!isImage && !isVideo) {
      alert(`文件 "${file.name}" 不是支持的图片或视频格式`);
      return;
    }

    if (file.size > maxSize) {
      alert(`文件 "${file.name}" 大小超过50MB`);
      return;
    }
  }

  uploading.value = true;
  uploadError.value = '';

  try {
    // 批量上传多个文件
    const res = await uploadProductImages(fileArray);
    if (res.success) {
      // 将上传成功的URL添加到图片列表
      formData.value.images = [...formData.value.images, ...res.data.urls];
      alert(`成功上传 ${res.data.count} 个文件！`);
    } else {
      uploadError.value = res.message || '上传失败';
      alert('上传失败: ' + (res.message || '未知错误'));
    }
  } catch (error) {
    console.error('上传失败:', error);
    uploadError.value = error.message || '上传失败，请重试';
    alert('上传失败: ' + (error.message || '网络错误，请重试'));
  } finally {
    uploading.value = false;
    // 清空文件输入，允许重复选择同一文件
    if (fileInput.value) {
      fileInput.value.value = '';
    }
  }
};

// 移除媒体文件
const removeMedia = (index) => {
  formData.value.images.splice(index, 1);
};

// 移动媒体文件位置
const moveMedia = (index, direction) => {
  const newIndex = index + direction;
  if (newIndex < 0 || newIndex >= formData.value.images.length) return;
  
  const temp = formData.value.images[index];
  formData.value.images[index] = formData.value.images[newIndex];
  formData.value.images[newIndex] = temp;
};

// 规格管理相关函数
const manageSpecs = async (product) => {
  currentProduct.value = product;
  showSpecModal.value = true;
  await loadSpecs();
};

const closeSpecModal = () => {
  showSpecModal.value = false;
  currentProduct.value = null;
  showSpecForm.value = false;
  editingSpec.value = null;
};

const loadSpecs = async () => {
  if (!currentProduct.value) return;
  
  try {
    const res = await getSpecs(currentProduct.value.id);
    if (res.success) {
      specs.value = res.data || [];
    }
  } catch (error) {
    console.error('加载规格失败:', error);
  }
};

const showAddSpec = () => {
  editingSpec.value = null;
  specFormData.value = {
    spec_name: '',
    spec_value: '',
    price: null,
    stock: -1,
    sort_order: 0,
    status: 1
  };
  showSpecForm.value = true;
};

const editSpec = (spec) => {
  editingSpec.value = spec;
  specFormData.value = {
    spec_name: spec.spec_name || '',
    spec_value: spec.spec_value || '',
    price: spec.price || null,
    stock: spec.stock !== undefined ? spec.stock : -1,
    sort_order: spec.sort_order || 0,
    status: spec.status !== undefined ? spec.status : 1
  };
  showSpecForm.value = true;
};

const cancelSpecForm = () => {
  showSpecForm.value = false;
  editingSpec.value = null;
};

const submitSpecForm = async () => {
  if (!specFormData.value.spec_name || !specFormData.value.spec_value) {
    alert('请填写规格名称和规格值');
    return;
  }

  try {
    const data = {
      product_id: currentProduct.value.id,
      ...specFormData.value,
      price: specFormData.value.price || null
    };

    let res;
    if (editingSpec.value) {
      res = await updateSpecApi(editingSpec.value.id, specFormData.value);
    } else {
      res = await createSpecApi(data);
    }

    if (res.success) {
      alert('操作成功');
      cancelSpecForm();
      await loadSpecs();
    } else {
      alert(res.message || '操作失败');
    }
  } catch (error) {
    console.error('提交规格失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

const deleteSpec = async (spec) => {
  if (!confirm(`确定要删除规格"${spec.spec_name}: ${spec.spec_value}"吗？`)) return;

  try {
    const res = await deleteSpecApi(spec.id);
    if (res.success) {
      alert('删除成功');
      await loadSpecs();
    } else {
      alert(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除规格失败:', error);
    alert('网络错误: ' + (error.message || '未知错误'));
  }
};

onMounted(() => {
  loadProducts();
  loadCategories();
});
</script>

<style scoped>
.product-management {
  max-width: 100%;
}

.product-thumb {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 4px;
}

.product-images-list {
  display: flex;
  align-items: center;
  gap: 4px;
}

.more-images {
  font-size: 12px;
  color: #666;
  padding: 4px 8px;
  background: #f5f5f5;
  border-radius: 4px;
}

.no-image {
  color: #999;
  font-size: 12px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e5e5;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.upload-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.media-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
  margin-bottom: 12px;
}

.media-item {
  position: relative;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.media-item img,
.media-item video {
  width: 100%;
  height: 150px;
  object-fit: cover;
  display: block;
}

.media-item .remove-media-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  z-index: 10;
}

.media-item .remove-media-btn:hover {
  background: #ff7875;
}

.move-media-btn {
  position: absolute;
  bottom: 4px;
  width: 24px;
  height: 24px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.move-media-btn:hover:not(:disabled) {
  background: rgba(0, 0, 0, 0.8);
}

.move-media-btn:disabled {
  opacity: 0.3;
  cursor: not-allowed;
}

.move-media-btn.move-up {
  left: 4px;
}

.move-media-btn.move-down {
  left: 32px;
}

.image-preview {
  position: relative;
  display: inline-block;
  max-width: 300px;
}

.image-preview img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #e5e5e5;
}

.image-preview video {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #e5e5e5;
}

.remove-image-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.remove-image-btn:hover {
  background: #ff7875;
}

.upload-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.upload-status {
  color: #1890ff;
  font-size: 12px;
}

.upload-error {
  color: #ff4d4f;
  font-size: 12px;
}

.upload-tip {
  margin-top: 4px;
  color: #999;
  font-size: 12px;
}

.image-url-input {
  margin-top: 8px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.actions {
  display: flex;
  gap: 8px;
}

.btn-sm {
  padding: 4px 12px;
  font-size: 12px;
}

/* 规格管理样式 */
.modal-large {
  max-width: 800px;
}

.spec-list {
  margin-bottom: 24px;
}

.spec-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.spec-list-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.spec-form {
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
  margin-top: 20px;
}

.spec-form h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
}
</style>
